package com.jdj.framework.core.base.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author caijinbang
 * @date 2019-04-13 15:44
 */
public class NetworkUtils {
    private static final Logger logger = LoggerFactory
        .getLogger(NetworkUtils.class);

    private static final String LOCAL_IP = "127.0.0.1";

    /**
     * 获取本机IP地址
     *
     * @return
     * @throws UnknownHostException
     * @throws SocketException
     */
    public static String getIpAddress() throws UnknownHostException,
        SocketException {
        Enumeration<?> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = (NetworkInterface) e.nextElement();
            Enumeration<?> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress ip = (InetAddress) ee.nextElement();
                String ipAddr = ip.getHostAddress();
                logger.info("ipAddr: " + ipAddr);
                if (ipAddr.indexOf(LOCAL_IP) == -1 && ipAddr.indexOf(".") != -1) {
                    logger.info("NetworkInterface find ip: " + ipAddr);
                    return ipAddr;
                }
            }
        }
        String ip = InetAddress.getLocalHost().getHostAddress().toString();
        logger.info("InetAddress.getLocalHost().getHostAddress() find ip: " + ip);
        return ip;
    }
}
